<template>
  <div v-if="modelValue" class="flex items-center justify-start" @click="open">
    <el-avatar :size="50" :src="toAbsoluteUrl(modelValue)" /><div class="ml-2 text-sm">点击图片进行替换</div>
  </div>
  <div v-else>
    <div class="w-[100px] h-[100px] bg-gray-100 flex justify-center items-center text-gray-400 rounded" @click="open">
      <el-icon :size="25">
        <Plus />
      </el-icon>
    </div>
    <div class="mx-2">{{ placeholder }}</div>
  </div>
  <el-dialog title="选择图片" custom-class="custom-dialog" v-model="dialogVisible" width="80%" top="5vh">
    <el-container class="bg-white rounded-lg">
      <el-header class="flex items-center justify-start" style="border-bottom: 1px solid #eeeeee;">
        <el-button type="primary" @click="onAddCatogery">新增图片分类</el-button>
        <el-button type="warning" @click="onAddImg">上传图片</el-button>
      </el-header>
      <el-container>
        <ImageAside ref="imageAsideRef" :cHeight="cHeight" @current-change="onChange" />
        <ImageMain ref="imageMainRef" :categoryId="categoryId" :cHeight="cHeight" :selectable="true" />
      </el-container>
    </el-container>
    <template #footer>
      <el-button @click="dialogVisible = false">Cancel</el-button>
      <el-button type="primary" @click="submit">OK</el-button>
    </template>
  </el-dialog>

</template>
<script setup>
import { ref } from 'vue'
import { useResizeObserver } from '@vueuse/core'
import ImageAside from './ImageAside.vue'
import ImageMain from './ImageMain.vue'
import { toAbsoluteUrl } from './../composables/util'
const dialogVisible = ref(false)

// 定义接收的 props
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请选择头像'
  }
});

// 定义触发的事件
const emit = defineEmits(['update:modelValue'])

// 当点击确定按钮的时候，触发事件
const submit = () => {
  emit('update:modelValue', imageMainRef.value.getSelectedImageUrl())
  dialogVisible.value = false
}

const open = () => {
  dialogVisible.value = true
}




// 选择图片弹出框
const imageAsideRef = ref(null)

const cHeight = ref(0)
const el = ref(null)

// 计算Image内容区域高度
const calHeight = () => {
  const windowHeight = window.innerHeight || document.body.clientHeight
  cHeight.value = (windowHeight - 60 - 40 - 170) * 0.8
}
calHeight()

// 监听el组件，即整个内容页面组件的尺寸发生变化
useResizeObserver(el, (entries) => {
  calHeight()
})

const imageMainRef = ref(null)
const categoryId = ref(0)
// 分类选中变化事件
const onChange = (id) => {
  categoryId.value = id
}

// 新增图片分类
const onAddCatogery = () => {
  imageAsideRef.value.addCatoyery()
}

// 新增图片上传
const onAddImg = () => {
  imageMainRef.value.openUploadFile()
}
</script>
<style scoped></style>